package com.example.meituan.activity.man;

import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;


import com.example.meituan.R;
import com.example.meituan.activity.bean.ShopCarBean;
import com.example.meituan.activity.man.adapter.ImageAdapter;
import com.example.meituan.activity.bean.AdminBean;
import com.example.meituan.activity.bean.ImgBean;
import com.example.meituan.activity.bean.ShopBean;

import com.example.meituan.activity.bean.TypeBean;
import com.example.meituan.dao.AdminDao;
import com.example.meituan.dao.ImgDao;
import com.example.meituan.dao.ShopCarDao;
import com.example.meituan.dao.ShopDao;
import com.example.meituan.dao.TypeDao;
import com.example.meituan.until.FileImgUntil;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

public class UpdateShopActivity extends AppCompatActivity  {

    private ActivityResultLauncher<String> getContentLauncher;
    private Uri url;
    AdminDao adminDao;
    TypeDao typeDao;
    AdminBean currentUser;
    String path;
    String shopId;
    ArrayList<String> imagePaths;
    private ImageAdapter imageAdapter;
    private int shopBean(String id,String businessId,String name,String des,String price,String type){
        ShopBean shopBean=new ShopBean();
        shopBean.setDes(des);
        shopBean.setName(name);
        shopBean.setPrice(price);
        shopBean.setId(id);
        shopBean.setType(type);
        shopBean.setBusinessId(businessId);
        int a= ShopDao.updateShop(shopBean);
        return a;
    }
    private void saveAllImagesToDatabase() {
        List<ImgBean> existingImages = ImgDao.getAllImagesByShopId(shopId);
        Set<String> existingPaths = existingImages.stream().map(ImgBean::getImg).collect(Collectors.toSet());

        // 首先删除不再存在的图片
        for (ImgBean img : existingImages) {
            if (!imagePaths.contains(img.getImg())) {
                int b=ImgDao.deleteImageById(img.getId());
                if(b!=0){
                    Toast.makeText(UpdateShopActivity.this, "删除原有图片成功", Toast.LENGTH_SHORT).show();
                }
                else{
                    Toast.makeText(UpdateShopActivity.this, "删除原有图片失败", Toast.LENGTH_SHORT).show();
                }
            }
        }

        // 然后插入新的或更新已有的图片
        for (String path : imagePaths) {
            if (!existingPaths.contains(path)) {
                String id= UUID.randomUUID().toString().replace("-","");
                // 创建 ImageBean 实例
                ImgBean imageBean = new ImgBean(id, shopId, path);

                // 插入到数据库
                int a=ImgDao.addImage(imageBean);
                if(a==1){
                    Toast.makeText(UpdateShopActivity.this, "保存图片成功", Toast.LENGTH_SHORT).show();
                }
                else{
                    Toast.makeText(UpdateShopActivity.this, "保存图片失败", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }


    final ActivityResultLauncher<String[]> multipleContentLauncher = registerForActivityResult(
            new ActivityResultContracts.OpenMultipleDocuments(),
            uris -> {
                if (uris != null && !uris.isEmpty()) {
                    for (Uri uri : uris) {
                        String path = FileImgUntil.getImgPath();
                        FileImgUntil.saveImageBitmapToFile(uri, UpdateShopActivity.this, path);

                        if (path != null) {
                            imagePaths.add(path);
                            imageAdapter.addImage(path);
                        } else {
                            Toast.makeText(UpdateShopActivity.this, "保存图片失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            });

    private void openMultipleGallery() {
        multipleContentLauncher.launch(new String[]{"image/*"});
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        getMenuInflater().inflate(R.menu.shop_delete,menu);
        return super.onCreateOptionsMenu(menu);
    }
    @Override
    public  boolean onOptionsItemSelected(MenuItem item){
        int id=item.getItemId();
        if(id==R.id.shop_delete){
           AlertDialog.Builder alertDialog=new AlertDialog.Builder(this);
           alertDialog.setTitle("删除商品");
           alertDialog.setMessage("确定删除该商品");
           alertDialog.setCancelable(false);
           alertDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
               @Override
               public void onClick(DialogInterface dialog, int which) {
                   dialog.dismiss();
               }
           });
           alertDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
               @Override
               public void onClick(DialogInterface dialog, int which) {
                   List<TypeBean> types=TypeDao.getAllTypesByShopId(shopId);
                   for(TypeBean i : types){
                       TypeDao.deleteTypeById(i.getId());
                   }
                   List<ImgBean> imgBeans=ImgDao.getAllImagesByShopId(shopId);
                   for(ImgBean i:imgBeans){
                       ImgDao.deleteImageById(i.getId());
                   }
                   List<ShopCarBean> shopCarBeans= ShopCarDao.findAllByShopId(shopId);
                   for(ShopCarBean i: shopCarBeans){
                       ShopCarDao.delete(i.getsId());
                   }
                   int a=ShopDao.deleteShopById(shopId);
                   if (a == 1) {
                       Toast.makeText(UpdateShopActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                   } else {
                       Toast.makeText(UpdateShopActivity.this, "删除失败", Toast.LENGTH_SHORT).show();
                   }
               }
           });
           AlertDialog alertDialog1=alertDialog.create();
           alertDialog1.show();
        }
        return true;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_update_shop);

        //实现一个返回的功能
        Toolbar toolbar=findViewById(R.id.update_shop_list_toolbar);
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                                                 @Override
                                                 public void onClick(View v) {
                                                     finish();

                                                 }
                                             }
        );






        imagePaths = new ArrayList<>();
        EditText nameText=findViewById(R.id.update_shop_list_name);
        EditText desText=findViewById(R.id.update_shop_list_des);
        EditText priceText=findViewById(R.id.update_shop_list_price);
        TextView update=findViewById(R.id.update_shop_list);
        TextView typeDes=findViewById(R.id.update_shop_list_type_des);
        Context context = this;

        SharedPreferences sharedPreferences = context.getSharedPreferences("data", Context.MODE_PRIVATE);

        SharedPreferences.Editor editor = sharedPreferences.edit();


        editor.apply();
        currentUser = adminDao.getUserInfo(context);
        shopId= UUID.randomUUID().toString().replace("-","");
        String businessId=currentUser.getUserId();
        ShopBean shopBean = (ShopBean) getIntent().getSerializableExtra("shopBean");
        if (shopBean != null) {
            nameText.setText(shopBean.getName());
            desText.setText(shopBean.getDes());
            priceText.setText(shopBean.getPrice());
            shopId=shopBean.getId();
        }
        androidx.recyclerview.widget.RecyclerView recyclerViewImages = findViewById(R.id.updaterecyclerViewImages);

        List<ImgBean> existingImages = ImgDao.getAllImagesByShopId(shopId);
        for (ImgBean img : existingImages) {
            imagePaths.add(img.getImg());
        }
        TextView addButton = findViewById(R.id.update_photo_updateshop);
        addButton.setOnClickListener(v -> openMultipleGallery());
        recyclerViewImages.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        imageAdapter = new ImageAdapter(this, imagePaths, position -> {
            imagePaths.remove(position);
            imageAdapter.removeImage(position);
        });
        recyclerViewImages.setAdapter(imageAdapter);
        Spinner spinner = findViewById(R.id.update_shop_list_type);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.shop_type_array));
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);

        String desiredValue = shopBean.getType();
        int position = adapter.getPosition(desiredValue);
        if (position >= 0) {
            spinner.setSelection(position, true);
        } else {
            Toast.makeText(UpdateShopActivity.this, "没有对应的类型", Toast.LENGTH_SHORT).show();
        }
        String finalShopId = shopId;
        typeDes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(typeDao==null){
                    typeDao=new TypeDao();
                }
                List<TypeBean> types = typeDao.getAllTypesByShopId(shopId);

                StringBuilder typeDescriptions = new StringBuilder();
                for (TypeBean type : types) {
                    typeDescriptions.append(type.getTypeDescription()).append("\n");
                }
                if (typeDescriptions.length() > 0 && typeDescriptions.charAt(typeDescriptions.length() - 1) == '\n') {
                    typeDescriptions.setLength(typeDescriptions.length() - 1);
                }

                LayoutInflater inflater = LayoutInflater.from(context);
                View dialogView = inflater.inflate(R.layout.dialog_edit_types, null);

                EditText editTypeDescriptions = dialogView.findViewById(R.id.edit_type_descriptions);
                Button btnCancel = dialogView.findViewById(R.id.btn_cancel);
                Button btnSubmit = dialogView.findViewById(R.id.btn_submit);

                editTypeDescriptions.setText(typeDescriptions.toString());

                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setView(dialogView);

                final AlertDialog alertDialog = builder.create();

                btnCancel.setOnClickListener(view -> alertDialog.dismiss());

                btnSubmit.setOnClickListener(view -> {

                    String updatedText = editTypeDescriptions.getText().toString();
                    String[] updatedLines = updatedText.split("\n");

                    for (TypeBean type : types) {
                        typeDao.deleteTypeById(type.getId());
                    }

                    for (String line : updatedLines) {
                        String trimmedLine = line.trim();
                        if (!trimmedLine.isEmpty()) {
                            String id= UUID.randomUUID().toString().replace("-","");
                            TypeBean newType = new TypeBean(id, shopId, trimmedLine);
                            typeDao.addType(newType);
                        }
                    }

                    alertDialog.dismiss();
                });


                alertDialog.show();

            }
        });
        update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name=nameText.getText().toString();
                String des=desText.getText().toString();
                String price=priceText.getText().toString();
                boolean isValid=true;
                boolean is=true;

                if(name.isEmpty())
                {
                    Toast.makeText(UpdateShopActivity.this, "商品名称不能为空", Toast.LENGTH_SHORT).show();
                    isValid = false;
                }
                if(price.isEmpty())
                {
                    Toast.makeText(UpdateShopActivity.this, "商品价格不能为空", Toast.LENGTH_SHORT).show();
                    isValid = false;
                }
                if(des.isEmpty())
                {
                    Toast.makeText(UpdateShopActivity.this, "商品描述不能为空", Toast.LENGTH_SHORT).show();
                    isValid = false;
                }
                Object selectedItem = spinner.getSelectedItem();
                String selectedType = selectedItem.toString();
                if (selectedType.isEmpty()) {
                    Toast.makeText(UpdateShopActivity.this, "商品类型不能为空", Toast.LENGTH_SHORT).show();
                    isValid = false;
                }

                if(isValid){
                    if(is) {
                        path = FileImgUntil.getImgPath();
                        FileImgUntil.saveImageBitmapToFile(url, UpdateShopActivity.this, path);
                    }
                    saveAllImagesToDatabase();
                    imagePaths.clear();
                    imageAdapter.notifyDataSetChanged();
                    int a = shopBean(finalShopId,businessId,name,des,price,selectedType);
                    if (a == 1) {
                        Toast.makeText(UpdateShopActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(UpdateShopActivity.this, "修改失败", Toast.LENGTH_SHORT).show();
                    }
                }


            }
        });
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
    }
}